<template>
  <div style="margin: 20px">
    <div
      style="display: flex; justify-content: space-between; font-size: 16px; border-bottom: 1px solid #ccc; padding-bottom: 5px"
    >
      <div>
        <span class="el-icon-tickets" style="margin-right: 15px"></span>
        <span>{{ title }}</span>
      </div>
      <div class="top-button">
        <el-button size="mini" @click="headSave()">保存</el-button>
        <el-button size="mini" @click="headSave(true)">保存并返回</el-button>
        <el-button size="mini" @click="headCancel">取消</el-button>
      </div>
    </div>

    <div style="margin: 10px 20px">
      <el-form :rules="rules" ref="ruleForm" :inline="true" :model="dataForm" label-width="100px" class="product-form">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称:" prop="productName">
              <el-input v-model="dataForm.productName" :disabled="readOnly" size="small" style="width: 100%;"
                        placeholder="请输入产品名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编码:" prop="productCode">
              <el-input v-model="dataForm.productCode" :disabled="readOnly" size="small" placeholder="请输入产品编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用:" prop="isEnable">
              <el-switch
                v-model="dataForm.isEnable"
                active-text="已启用"
                :disabled="true"
                :active-value="1"
                :inactive-value="0"
                size="small"
                inactive-text="未启用"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="协议类型:" prop="agreementType">
              <el-select v-model="dataForm.agreementType" :disabled="this.$route.query.type!=='add'"
                         style="width: 100%;" size="small"
              >
                <el-option
                  v-for="item in aTDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="产品图片:">
              <el-upload
                :action="uploadPath"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :limit="1"
                :show-file-list="true"
                :file-list="fileList"
                :headers="headers"
                :disabled="this.$route.query.type == 'view'"
                accept=".jpeg, .jpg, .png"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16" class="remark">
            <el-form-item label="备注:">
              <el-input type="textarea" :rows="6" :disabled="readOnly" v-model="dataForm.remark" maxlength="500"
                        show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-dialog :visible.sync="uploadDialogVisible">
      <img width="100%" :src="dataForm.image" alt="">
    </el-dialog>
    <template>
      <div>
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="点位信息" name="point">
            <div
              style="display: flex; justify-content: space-between; font-size: 16px; border-bottom: 1px solid #ccc; padding-bottom: 5px">
              <div>
                <span class="el-icon-tickets" style="margin-right: 15px"></span>
                <span>点位信息</span>
              </div>
              <div v-if="!readOnly">
                <el-button size="mini" @click="headAdd()">新增</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="关联设备" v-if="type != 'add'" name="relatedDevices">
            <div
              style="display: flex; justify-content: space-between; font-size: 16px; border-bottom: 1px solid #ccc; padding-bottom: 5px">
              <div>
                <span class="el-icon-share" style="margin-right: 15px"></span>
                <span>关联设备信息</span>
              </div>
            </div>
            <equipment ref="equipment"></equipment>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>


    <div v-if="activeTab === 'point'">
      <el-row style="margin-top: 25px" :gutter="20">
        <div class="point-DA point-card">
          <el-col :span="6" v-for="(item, index) in tableData" :key="index">
            <el-card shadow="hover" style="font-size: 14px">
              <div class="point-head" style="position: relative;font-size: 20px; margin-bottom: 10px">
                {{ item.pointName }}
                <span
                  :style="{
						  			display: 'inline-block',
						  			height: '8px',
						  			width: '8px',
										background: item.isEnable === 1 ? 'rgb(10, 191, 91)' : 'rgb(229, 69, 69)',
						  			borderRadius: '7px',
						  			verticalAlign: 'middle',
						  			marginLeft: '10px',
						  			marginBottom: '5px'}">
              </span>
                <el-tooltip class="item" v-if="!readOnly" effect="dark" content="编辑" placement="top">
                  <a style="font-size: 14px; position: absolute; right: 0" @click="rowEdit(item)">
                    <span class="el-icon-edit" style="font-size: 18px;color: #1677FF"></span>
                  </a>
                </el-tooltip>
              </div>
              <div class="point-content" style="margin-bottom: 5px">
                <div style="margin: 16px 6px 0 6px">
                  <span style="color: #646a73">点位编码：</span>
                  <span style="color: #1677ff">{{ item.pointCode }}</span>
                </div>
                <div style="margin: 16px 6px 0 6px">
                  <span style="color: #646a73">创建时间：</span>
                  <span style="color: #1677ff">{{ parseTime(item.createTime) }}</span>
                </div>
              </div>
              <el-divider v-if="!readOnly"></el-divider>
              <div style="margin-top: 5px;float: right">
                <div v-if="!readOnly">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="rowRemove(item)"
                    style="margin: 5px"
                  >删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </div>
      </el-row>

      <el-empty
        v-if="tableData.length==0"
        style="width: 100%"
        description="暂无数据"
        :image-size="120"
      ></el-empty>
      <div class="block" style="float: right;" v-if="page.total !== 0">
        <el-pagination
          background
          :current-page="page.currentPage"
          :page-sizes="[8, 16, 32, 64, 128]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <opcda-dialog
      ref="opdc"
      @restOnLoad="restOnLoad"
    >
    </opcda-dialog>
  </div>

</template>

<script>
import {detail, submit} from '@/api/cps/product-api'
import {page as getPage, remove} from '@/api/cps/product-point-api'
import OpcdaDialog from '@/views/cps/product/components/OpcdaDialog.vue'
import {DICT_TYPE} from '@/utils/dict'
import {getAccessToken} from '@/utils/auth'
import equipment from '@/views/cps/product/components/equipmentComponents.vue'


export default {
  name: 'add',
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  components: {
    OpcdaDialog,
    equipment
  },
  data() {
    return {
      activeTab: 'point',
      tabs: [
        {
          label: '点位信息',
          name: 'point',
        },
        {
          label: '关联设备',
          name: 'device',
        },
      ],
      fileList: [],
      headers: {Authorization: "Bearer " + getAccessToken()}, // 设置上传的请求头部
      uploadDialogVisible: false,
      uploadPath: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/upload',
      title: '产品新增',
      readOnly: false,
      type: 'view',
      dataForm: {},
      tableData: [],
      // 用于判断是否超出容器
      isTextOverflow: false,
      aTDict: [], // 协议类型
      rules: {
        productName: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ],
        productCode: [
          {
            required: true,
            message: '请输入产品编码',
            trigger: 'blur'
          }
        ],
        agreementType: [
          {
            required: true,
            message: '请选择协议类型',
            trigger: 'blur'
          }
        ]
      },
      dictBizMap: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      }
    }
  },
  created() {
    let {id, type} = this.$route.query
    this.type = type
    this.getDictBiz()
    if (['edit'].includes(this.type)) {
      this.dataForm.id = id
      this.title = '产品编辑'
      this.initData()
      this.onLoad(this.page)
    }
    if (['view'].includes(this.type)) {
      this.dataForm.id = id
      this.readOnly = true
      this.title = '产品查看'
      this.initData()
      this.onLoad(this.page)
    }
  },
  mounted() {
    this.aTDict = this.$store.state.dict.dictDatas.agreement_type
    const type = this.$route.query.type;
    if (type === 'add') {
      this.$tab.updatePage(Object.assign({}, this.$route, {title: '产品新增'}));
    } else if (type === 'edit') {
      this.$tab.updatePage(Object.assign({}, this.$route, {title: '产品编辑'}));
    } else {
      this.$tab.updatePage(Object.assign({}, this.$route, {title: '产品查看'}));
    }
  },
  methods: {
    addDevice() {
      if (!this.dataForm.id) {
        this.$message.warning("请先保存产品信息");
        return;
      }
      this.$refs.equipment.headAdd()
    },
    handleTabClick(tab, event) {
      if (tab.name === 'relatedDevices') {
        this.equipment();
      }
    },
    equipment() {
      this.$refs.equipment.getEquipment(this.dataForm.productCode)
    },
    //文件上传个数
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一个文件`);
    },
    handleSuccess(response, file, fileList) {
      this.dataForm.image = response.data
    },
    handleRemove(file, fileList) {
      this.dataForm.image = ""
    },
    handlePictureCardPreview(file) {
      this.dataForm.image = file.url
      this.uploadDialogVisible = true;
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.onLoad(this.page)
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.onLoad(this.page)
    },
    getDictBiz() {
      const pointDict = this.$store.state.dict.dictDatas.point_data_type
      this.dictBizMap = new Map(pointDict.map((item) => [item.label, item.value]))
    },
    restOnLoad() {
      this.onLoad(this.page)
    },
    headAdd() {
      if (!this.dataForm.id) {
        this.$message.warning('请先保存产品信息')
        return
      }
      this.$refs.opdc.addPoint(this.dataForm.id)
    },
    headCancel() {
      this.$router.back()
    },
    initData() {
      detail(this.dataForm.id).then((res) => {
        this.dataForm = res.data
        if (res.data.image !== "" && res.data.image !== null) {
          let file = {url: res.data.image}
          this.fileList.push(file)
        }
      })
    },
    headSave(cancel = false) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$loading()
          submit(this.dataForm)
            .then((res) => {
              if (res.code === 0) {
                this.$message.success('操作成功')
              } else {
                this.$message.success(msg)
              }
              if (cancel) {
                this.$router.back()
              } else {
                //刷新数据
                Object.assign(this.dataForm, res.data);
                this.dataForm = data
                this.initData()
                this.type = 'edit'
              }
            })
            .finally(() => {
              this.$loading().close()
            })
        }
      })
    },
    onLoad(page, params = {}) {
      this.page = page
      this.tableLoading = true;
      if (this.dataForm.id) {
        params.productId = this.dataForm.id
      }
      getPage(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data
        this.page.total = data.total
        data.records.forEach((item) => {
          item.dataTypeLabel = this.dictBizMap.get(item.dataType)
        })
        this.tableData = data.records
        this.tableLoading = false;
      })
    },
    rowEdit(row) {
      this.$refs.opdc.editPoint(row)
    },
    rowRemove(row) {
      this.$confirm('确定将选择数据删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id)
        })
        .then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        })
    }
  }
}
</script>
<style scoped lang="scss">
.point-card ::v-deep .el-card__body {
  padding: 15px 20px 5px 20px !important;
}

.point-card ::v-deep .el-divider--horizontal {
  margin: 0;
}

.top-button ::v-deep .el-button + .el-button {
  margin-left: 0;
}

.product-form ::v-deep .el-textarea__inner {
  resize: none;
  min-height: 111.6px !important;
}

.product-form ::v-deep .el-form-item {
  width: 100%;
}

.product-form ::v-deep .el-form-item__content {
  width: calc(100% - 100px);
}

.product-form ::v-deep .el-form-item__label {
  color: #3f4448;
  font-weight: 400;
}

.cardBigBox {
  width: calc(100% - 24px);
  padding: 12px;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  background-color: #ffffff;
  align-content: flex-start;

  .cardbox {
    width: 24%;
    box-shadow: 0 0 5px #dde9ef;
    border: 1px solid #e7eff3;
    border-radius: 10px;
    margin: 16px 6px 0 6px;
    cursor: pointer;

    .cardTop {
      padding: 16px;

      .topContent {
        .instruction {
          white-space: nowrap; /* 防止文本换行 */
          overflow: hidden; /* 隐藏超出容器的文本 */
          text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
          cursor: pointer; /* 当鼠标悬停时显示手形光标，提示用户有tooltip */
          font-size: 20px;
          color: #333;
          text-align: center;
        }

        .topItem {
          font-size: 15px;
          color: #666;
          line-height: 30px;
        }
      }
    }

    .cardBottom {
      font-size: 14px;
      line-height: 25px;
      display: flex;
      border-top: 1px solid #dcdfe6;
      justify-content: space-between;

      .statusContent {
        display: flex;
        align-items: center;

        .iconCard {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: red;
          margin: 10px 6px;
        }
      }
    }
  }
}

.block {
  //position: absolute;
  bottom: 0;
  width: calc(100% - 48px);
  padding: 12px 24px;
  background-color: #ffffff;
  display: flex;
  flex-direction: row-reverse;
}
</style>
